<?php

namespace Home\Controller;

use Common\Controller\BaseController;
use Common\Model\UserModel;

class IndexController extends BaseController {

    /**
     * 主页：展示主页页面
     */
    public function index(){
        $this->display();
    }

    /**
     * 展示登陆页面
     */
    public function login(){
        if(UID){
            $this->redirect('@doc.wooo.wang');
        }
        $this->display();
    }

    /**
     * qq登陆
     */
    public function qqlogin(){
        $appId = C('QQ_LOGIN_CONFIG')['appid'];
        $callback = C('QQ_LOGIN_CONFIG')['callback'];
        $dialogUrl = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
            . $appId . "&redirect_uri=" . urlencode($callback);
        header('Location:'.$dialogUrl);
    }

    /**
     * QQ登陆回调方法
     */
    public function qqlogincallback(){
//        preg_match('/\?code=(\w+)/', $_SERVER['REQUEST_URI'], $decodeCodeResult);
//        $code = $decodeCodeResult[1];
        $code = I('get.code', '');
        if(!$code){
            $this->error('系统出现异常，QQ登陆失败');
        }
        $appId = C('QQ_LOGIN_CONFIG')['appid'];
        $appKey = C('QQ_LOGIN_CONFIG')['appkey'];
        $callback = C('QQ_LOGIN_CONFIG')['callback'];
        //Step2：通过Authorization Code获取Access Token
        $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="
            .$appId."&redirect_uri=".urlencode($callback)."&client_secret=".$appKey."&code=".$code;
        $response = file_get_contents($token_url);
        if (strpos($response, "callback") !== false) {
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response  = substr($response, $lpos + 1, $rpos - $lpos - 1);
            $msg = json_decode($response, true);
            if (isset($msg['error'])) {
                $this->error('QQ登陆失败['.$msg['error'].']：'.$msg['error_description']);
            }
        }
        //Step3：使用Access Token来获取用户的OpenID
        $params = array();
        parse_str($response, $params);
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
        $str  = file_get_contents($graph_url);
        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
        }
        $qqInfo = json_decode($str, true);
        if (isset($qqInfo['error'])) {
            $this->error('QQ登陆失败['.$qqInfo['error'].']：'.$qqInfo['error_description']);
        }
        // 判断用户是否已经存在，如果还未存在则创建用户
        $uid = UserModel::checkUserByOpenId($qqInfo['openid']);
        if(!$uid){
            $userInfoUrl = "https://graph.qq.com/user/get_user_info?access_token=".$params['access_token']
                .'&oauth_consumer_key='.$appId.'&openid='.$qqInfo['openid'];
            $userInfo  = json_decode(file_get_contents($userInfoUrl), true);
            $data = array(
                'openid' => $qqInfo['openid'],
                'nick' => $userInfo['nickname'] ? : '未命名'.time(),
                'sex' => $userInfo['gender'] === '男' ? 1 : 0,
                'province' => $userInfo['province'],
                'city' => $userInfo['city'],
                'year' => $userInfo['year'],
                'create' => time()
            );
            $avatar = $userInfo['figureurl_qq_2'] ? : $userInfo['figureurl_qq_1'];
            if ($avatar) {
                $data['avatar'] = $avatar;
            }
            $uid = UserModel::addData($data);
            if(!$uid){
                $this->error('QQ登陆失败，请刷新后再试');
            }
        }
        // 进行登陆操作
        $data = array('uid' => $uid);
        $token = encodeSimpleJwt($data);
        cookie('token', $token, 1296000);
        $this->success('QQ登陆成功！', U('@doc.wooo.wang'));
    }

    /**
     * 退出登录
     */
    public function logout(){
        cookie('token', null);
        $this->redirect('@doc.wooo.wang');
    }
}